package com.sddr.common.aoollo.api;

import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.google.common.collect.Sets;
import org.springframework.beans.factory.DisposableBean;
import com.ctrip.framework.apollo.Config;

import java.util.ArrayList;
import java.util.List;


/**
 * @author 山顶洞人郑某
 * @className ApolloApi.java
 * @date 2025 07 13
 */
public class ApolloApi implements DisposableBean {

    public final Config apolloConfig; //阿波罗配置类
    //配置监听器集合
    private final List<ConfigChangeListener> configChangeListenerList = new ArrayList<>();

    public ApolloApi(Config apolloConfig) {
        this.apolloConfig = apolloConfig;
    }

    public String getConfig(String dataId, String group) {
        return apolloConfig.getProperty(dataId, group);
    }
    /**
     *
     * Invoked by the containing {@code BeanFactory} on destruction of a bean.
     *
     * @throws Exception in case of shutdown errors. Exceptions will get logged
     *                   but not rethrown to allow other beans to release their resources as well.
     */
    @Override
    public void destroy() throws Exception {
        if (configChangeListenerList.size() > 0) {
            for (final ConfigChangeListener configChangeListener : configChangeListenerList) {
                apolloConfig.removeChangeListener(configChangeListener);
            }
        }
    }

    public ConfigChangeListener listenConfig(String dataId, String group, ApolloListen apolloListen) {
        ConfigChangeListener configChangeListener = changeEvent -> {
            ConfigChange configChange = changeEvent.getChange(group +"-" + dataId);
            String config = configChange.getNewValue();
            apolloListen.callback(config);
        };
        apolloConfig.addChangeListener(configChangeListener, Sets.newHashSet(group+"-"+dataId));
        return configChangeListener;
    }
}
